//
//  KABMineUserListVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/16.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMineUserListVC.h"
#import "KABMineUserListTCell.h"
#import <MJRefresh.h>
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "KABModel.h"
#import "MBProgressHUD+XDPrompt.h"
#import <UIScrollView+EmptyDataSet.h>
#import "KABHomepageVC.h"

@interface KABMineUserListVC ()<UITableViewDelegate, UITableViewDataSource, KABMineUserListTCellDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (assign, nonatomic) KABMineUserListVCType viewType;
@property (strong, nonatomic) KABMineUserList *userList;

@end

static NSString *const kReuseCellId = @"KABMineUserListTCell";
static NSInteger const kRequestUserSize = 20;

@implementation KABMineUserListVC

#pragma mark - life cycle
- (instancetype)initWithViewType:(KABMineUserListVCType)viewType {
    self = [super init];
    if (self) {
        _viewType = viewType;
    }
    return self;
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    NSArray *titleArray = @[@"我的关注", @"我的粉丝", @"黑名单管理"];
    self.navigationItem.title = titleArray[self.viewType];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 90.0;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"空空如也" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.userList.user_list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABMineUserListTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.userList.user_list.count) {
        [cell configViewWithUserItem:self.userList.user_list[indexPath.row]];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 5.9;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return 0.1;
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    KABMineUserItem *item = self.userList.user_list[indexPath.row];
    [self jumpToHomepageWithUserId:item.user_id userName:item.nick_name];
}

#pragma mark - KABMineUserListTCellDelegate
- (void)kABMineUserListTCell:(KABMineUserListTCell *)cell portraitTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    KABMineUserItem *item = self.userList.user_list[indexPath.row];
    [self jumpToHomepageWithUserId:item.user_id userName:item.nick_name];
}

- (void)kABMineUserListTCell:(KABMineUserListTCell *)cell followBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABMineUserItem *item = self.userList.user_list[indexPath.row];
    BOOL is_follow = (item.follow_state & 0x01);
    
    [self requestFollowWithFollowerId:item.user_id isFollow:!is_follow success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        NSLog(@"请求关注返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            item.follow_state = ((item.follow_state & 0x02) | (!is_follow));
            [self.tableView beginUpdates];
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.tableView endUpdates];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    }];
}

#pragma mark - event response
#pragma mark - private methods
- (void)jumpToHomepageWithUserId:(NSInteger)uid userName:(NSString *)userName {
    KABHomepageVC *vc = [[KABHomepageVC alloc] init];
    vc.user_id = uid;
    vc.user_name = userName;
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.userList.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestUserListWithHeader:isHeader];
}

- (KABMineUserList *)userListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.userList;
    }
    
    KABMineUserList *temp = [KABMineUserList yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.userList;
    }
    
    if (AddMore && self.userList) {
        [self.userList addMoreWithData:temp];
    } else {
        self.userList = temp;
    }
    return self.userList;
}

#pragma mark - network request
- (void)requestUserListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger startIndex = isHeader ? 0 : self.userList.user_list.count;
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"visitor_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"index" : @(startIndex),
                           @"size" : @(kRequestUserSize)};
    NSLog(@"请求粉丝、爱豆的参数：%@", pars);
    NSString *urlStr = (self.viewType == KABMineUserListVCTypeFollow) ? [ApiManager apiMineFollow] : [ApiManager apiMineFan];
    [[XDAFNetworking sharedInstance] GET:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求粉丝、爱豆返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self userListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求粉丝、爱豆失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestFollowWithFollowerId:(NSInteger)followerId isFollow:(BOOL)isFollow success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success {
    // 关注必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 关注请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"follower_id" : @(followerId),
                           @"is_follow" : isFollow ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiFollow] parameters:pars progress:nil success:success failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求关注失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
